﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace test1
{
    /// <summary>
    /// 单个文件下载，通过base64编码
    /// </summary>
    public partial class gzipXmlDownLoad : Form
    {
        public gzipXmlDownLoad()
        {
            string _getXMLURL = "http://update.365pub.net/webservice/OutPut.aspx?at=updatefiles&as=getupdatefile&file=\HeroMonitoring.exe";
            System.Xml.XmlDocument _doc = new System.Xml.XmlDocument();
            _doc = (System.Xml.XmlDocument)ProcessItem(_getXMLURL);
            //Console.WriteLine(_doc.InnerXml);
            string _fileName; 
            string _fileBase64;
            XmlNodeList _xmlItem;
            _xmlItem = _doc.DocumentElement.GetElementsByTagName("file");
            foreach (XmlElement _Item in _xmlItem) {
                _fileName = _Item.Attributes["name"].Value;
                _fileBase64 = _Item.Attributes["Base64"].Value;
                StrToFile(_fileBase64, _fileName);
            }


            InitializeComponent();
        }

        /// <summary>
        /// 把经过base64编码的字符串保存为文件
        /// </summary>
        /// <param name="base64String">经base64加码后的字符串</param>
        /// <param name="fileName">保存文件的路径和文件名</param>
        /// <returns>保存文件是否成功</returns>
        public static bool StrToFile(string base64String, string fileName)
        {
            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
            bw.Write(Convert.FromBase64String(base64String));
            bw.Close();
            fs.Close();
            return true;
        }
        public object ProcessItem(string URL)
        {
            //使用rssURL的值建立了一个WebRequest项
            System.Net.WebRequest myRequest = System.Net.WebRequest.Create(URL);
            //WebRequest请求的响应将会被放到一个WebResponse对象myResponse里,然后这个WebResponse对象被用来建立一个流来取出XML的值
            System.Net.WebResponse myResponse = myRequest.GetResponse();
            System.IO.Stream stream = myResponse.GetResponseStream();
            //使用一个XmlDocument对象rssDoc来存储流中的XML内容。XmlDocument对象用来调入XML的内容
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(stream);
            return doc;
        }
    }
}
